import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../../../../common/constants';

import Helper from '../../../../components/Helper';
import color from '../color';
import Box from '../Box';
import s from './CategoryTable.module.css';
import BarTable from '../../../../components/BarTable';

export default function CategoryTable({ className, stats }) {
	let rs = [].concat(stats);
	rs = rs.sort(
		(a, b) => new Date(b.endTime).getTime() - new Date(a.endTime).getTime()
	);
	const data = Object.values(
		Object.entries(WARNING_CATEGORY_KEY_LABEL_MAP.content).reduce(
			(obj, [key, label]) => {
				if (!obj[key]) obj[key] = { name: label, value: 0 };
				rs.forEach(x => {
					obj[key].value += x?.result?.stats?.[key] || 0;
				});
				return obj;
			},
			{}
		)
	)
		.sort((a, b) => b.value - a.value)
		.map((x, i) => ({ ...x, color: color[i % color.length] }));

	return (
		<Box
			title={
				<>
					内容违规类型统计
					<Helper overlay="按风险URL统计" placement="top" />
				</>
			}
			className={cn(className, s.trend)}
			headerClass={s.header}
		>
			<BarTable
				className={cn(s.table, 'tableFormat')}
				nameColName="威胁名称"
				barColName="发现次数"
				data={data}
			/>
		</Box>
	);
}

CategoryTable.propTypes = {
	className: PropTypes.string,
	stats: PropTypes.arrayOf(
		PropTypes.shape({
			target: PropTypes.string,
			name: PropTypes.string,
			endTime: PropTypes.string,
		})
	),
	jobId: PropTypes.string,
};

CategoryTable.defaultProps = {
	className: s.vulTrend,
};
